<?php
/**
 * @author mahao 2021-12-07
 * @version 1
 *
 */
namespace app\Api\controller;

use think\Db;
use app\Api\controller\Base;
class Login extends Base
{

    /**
     * 登录函数
     * @return void string 是否登录成功json
     */
    public function login(){
        $param = input();
        $log_data['name'] = $param['name'];
        // 查询用户名的盐
        $salt = Db::name('user')->where('name',$log_data['name'])->field('salt')->select();
        // 密码加盐
        $log_data['password'] = md5($param['passwd'].$salt[0]['salt']);

        $succ = model('LoginModel')->log($log_data);
        if($succ){
            //登录成功设置token
            $jwt_data = [
                'iss' => 'vue',
                'iat' =>time(),
                'exp' =>time()+21600,  //半天
                'nbf' =>'user',
                'jti' => md5(uniqid('JWT').time()),
                'user_info'=> [
                    'id'=>$succ[0]['id'],
                    'name'=>$succ[0]['name'],
                ],
            ];
            $jwt = new Jwt();
            $token = $jwt->getToken($jwt_data);
            $data = [
                'token' =>$token,
                'name' =>$succ[0]['name'],
            ];
            re_json(1,'登录成功',$data);
        }else{
            re_json(0,'用户名密码不正确');
        }
    }

    /**
     * 注册函数
     * @return string 是否注册成功json
     */
    public function regdit(){
        $parame['name'] = input('post.name');
        $parame['password'] = input('post.passwd');
        // 简单过滤
        $filtar = short_filter($parame);
        // 加盐
        $salt_str = salt(15);
        $user_exists = Db::name('user')->where('name',$parame['name'])->select();
        if ($user_exists){
            re_json(0,'用户名已存在');
        }
        $up_data = array(
            'name'=>$filtar['name'],
            'password'=>md5($filtar['password'].$salt_str),
            'salt' => $salt_str,
            'create_time'=>time(),
        );
       $succ =  model('LoginModel')->reg($up_data);
       if($succ){
           re_json(1,'添加成功',$parame['name']);
       }else{
           re_json(0,'添加失败');
       }
    }








}


